package com.orange.cepmanagerweb.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Component;

import com.orange.cepmanagerweb.model.Phone;

/**
 * Util class. Contains some common methods that can be used
 * for any class
 * 
 * @author Loiane Groner
 * http://loianegroner.com (English)
 * http://loiane.com (Portuguese)
 */
@Component
public class Util {
	
	/**
	 * Get list of Phones from request.
	 * @param data - json data from request 
	 * @return list of Phones
	 */
	public List<Phone> getPhonesFromRequest(Object data){

		List<Phone> list;

		//it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1){

			list = getListPhonesFromJSON(data);

		} else { //it is only one object - cast to object/bean

			Phone Phone = getPhoneFromJSON(data);

			list = new ArrayList<Phone>();
			list.add(Phone);
		}

		return list;
	}

	/**
	 * Transform json data format into Phone object
	 * @param data - json data from request
	 * @return 
	 */
	private Phone getPhoneFromJSON(Object data){
		JSONObject jsonObject = JSONObject.fromObject(data);
		Phone newPhone = (Phone) JSONObject.toBean(jsonObject, Phone.class);
		return newPhone;
	}

	/**
	 * Transform json data format into list of Phone objects
	 * @param data - json data from request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<Phone> getListPhonesFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<Phone> newPhones = (List<Phone>) JSONArray.toCollection(jsonArray,Phone.class);
		return newPhones;
	}

	/**
	 * Tranform array of numbers in json data format into
	 * list of Integer
	 * @param data - json data from request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Integer> getListIdFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<Integer> idPhones = (List<Integer>) JSONArray.toCollection(jsonArray,Integer.class);
		return idPhones;
	}
	
	@SuppressWarnings("unchecked")
	public List<String> getListIdStringFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<String> idPhones = (List<String>) JSONArray.toCollection(jsonArray,Integer.class);
		return idPhones;
	}
}
